package com.im.chat.controller;


import com.im.chat.base.BasePagination;
import com.im.chat.controller.util.AdminDto;
import com.im.chat.controller.util.AdminRedisCache;
import com.im.chat.dto.*;
import com.im.chat.login.UserDto;
import com.im.chat.model.*;
import com.im.chat.service.*;
import com.im.chat.util.*;
import com.im.chat.util.biz.ImagePropertiesConfig;
import com.im.chat.util.cache.redis.RedisCache;
import com.im.chat.util.file.FileIOUtils;
import com.im.chat.util.jsonp.CommonConstant;
import com.im.chat.util.jsonp.Jsonp;
import com.im.chat.util.jsonp.Jsonp_data;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 */
@RequestMapping("/chatadmin")
@RestController
public class ChatAdminRestController {
    @Autowired
    private ChatSessionService chatSessionService;
    @Autowired
    private ChatRecordService chatRecordService;
    @Autowired
    private ResourceService resourceService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private AuthUserService authUserService;
    /**
     * 管理员聊天搜索
     * @param adminSid
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @ResponseBody
    public Object loadHistoryMsg(
            @RequestParam(name = "adminSid", required = true) String adminSid,
            @RequestParam(name = "searchName", required = true) String searchName
    ) {
        if (StringUtils.isEmpty(adminSid)){
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        Long adminId = user.getAdminId();
        List<ChatAdminSearchDto> searchDtos = new ArrayList<ChatAdminSearchDto>();
        List<Long> chatIds  = chatRecordService.getChatIdsBySearchNameAndAdminId(searchName,adminId);
        for(Long chatId:chatIds){
            List<ChatRecord>  chatRecords = chatRecordService.getChatRecordBySearchName(searchName,adminId,chatId);
            List<ChatRecordDto> chatRecordDtos = ChatRecordDto.transDtos(chatRecords);
            Collections.reverse(chatRecordDtos);
            ChatSession chatSession = chatSessionService.getChatSessionByChatId(chatId);
            if(chatSession==null){
                continue;
            }
            ChatUserDto chatUserDto = this.getChatUserDto(chatSession.getMemberId());
            ChatAdminSearchDto chatAdminSearchDto = new ChatAdminSearchDto();
            chatAdminSearchDto.setChatUserDto(chatUserDto);
            chatAdminSearchDto.setRecordNum(chatRecordDtos.size());
            chatAdminSearchDto.setChatId(chatId);
            chatAdminSearchDto.setChatRecordDtos(chatRecordDtos);
            searchDtos.add(chatAdminSearchDto);
        }
        return Jsonp_data.success(searchDtos);
    }



    /**
     * 某个客户的历史聊天信息
     * @param adminSid
     * @param requestTimePoint
     * @param pageSize
     *  @param rollType  // up--->加载当前时间之前的数据 down 加载当前时间之后的数据
     * @return
     */
    @RequestMapping(value = "/loadHistoryMsg", method = RequestMethod.GET)
    @ResponseBody
    public Object loadHistoryMsg(
            @RequestParam(name = "adminSid", required = true) String adminSid,
            @RequestParam(name = "chatId", required = true) long chatId,
            @RequestParam(name = "requestTimePoint", required = true, defaultValue = "") String requestTimePoint,
            @RequestParam(name = "rollType", required = false, defaultValue = "up") String rollType,
            @RequestParam(name = "pageSize", required = false, defaultValue = PageConstant.APP_PAGE_SIZE + "") Integer pageSize
    ) {
        if (StringUtils.isEmpty(adminSid)){
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }

        //通过ChatId 获得到chatSession
        ChatSession chatSession = chatSessionService.findById(chatId);

        BasePagination<ChatRecord> page = new BasePagination<>();
        page.setLimit(pageSize);
        List<ChatRecordDto> chatRecordDtos = ChatRecordDto.transDtos(chatRecordService.selectByAdmin(chatId,requestTimePoint,rollType,pageSize));

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("userInfo", this.getChatUserDto(chatSession.getMemberId()));
        resultMap.put("adminInfo",this.getChatAdminDto(chatSession.getAdminId()));

        resultMap.put("msgList",chatRecordDtos);

        if(null!=chatRecordDtos&&chatRecordDtos.size()>0){
            if(rollType.equals("down")){
                resultMap.put("requestTimePoint",chatRecordDtos.get(chatRecordDtos.size()-1).getCreateTime());
            }else{
                Collections.reverse(chatRecordDtos);
                resultMap.put("requestTimePoint",chatRecordDtos.get(0).getCreateTime());
            }
        }else{
            resultMap.put("requestTimePoint",requestTimePoint);
        }
        resultMap.put("chatId",chatId);

        return Jsonp_data.success(resultMap);
    }


    /**
     * 加载所有的会话信息
     * @param adminSid
     * @return
     */
    @RequestMapping(value = "/loadAllSessionInfos", method = RequestMethod.GET)
    @ResponseBody
    public Object loadAllSessionInfos(
            @RequestParam(name = "adminSid", required = true) String adminSid
    ) {
        if (StringUtils.isEmpty(adminSid)) {
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)) {
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        long adminId = user.getAdminId();


        List<Map<String, Object>> sessionList = new ArrayList<>();
        List<ChatSession> chatSessionList = chatSessionService.selectByAdmin(adminId);
        for (ChatSession chatSession : chatSessionList) {
            Map<String, Object> sessionInfoMap = new HashMap<>();
            List<ChatRecordDto> chatRecordDtos = ChatRecordDto.transDtos(chatRecordService.selectByAdmin(chatSession.getId(), "n","up", ChatConstant.RECORD_DEF_PAGE_SIZE));
            if (null != chatRecordDtos && chatRecordDtos.size() > 0) {
                sessionInfoMap.put("requestTimePoint", chatRecordDtos.get(0).getCreateTime());
            } else {
                sessionInfoMap.put("requestTimePoint", DateFormat.dateToString(new Date()));
            }
            //通过chatId 和adminId获取未读数量
            int unreadnum = chatRecordService.getAdminUnReadRecord(chatSession.getId(),adminId);
            sessionInfoMap.put("unreadnum", unreadnum);
            sessionInfoMap.put("isTop", chatSession.getIsTop());
            sessionInfoMap.put("topTime", DateFormat.dateToString(chatSession.getTopTime()));
            sessionInfoMap.put("isCloseMSGRemind", chatSession.getIsCloseMsgRemind());
            sessionInfoMap.put("chatId", chatSession.getId());
            Collections.reverse(chatRecordDtos);
            sessionInfoMap.put("msgList", chatRecordDtos);
            sessionInfoMap.put("adminInfo",this.getChatAdminDto(chatSession.getAdminId()));
            sessionInfoMap.put("userInfo", this.getChatUserDto(chatSession.getMemberId()));
            sessionList.add(sessionInfoMap);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("sessionList", sessionList);
        return Jsonp_data.success(resultMap);
    }


    public ChatAdminDto getChatAdminDto(Long adminId){
        ChatAdminDto chatAdminDto = new ChatAdminDto();
        AuthUser authUser = authUserService.findById(adminId);
        if(authUser!=null){
            chatAdminDto.setAdminId(adminId);
            chatAdminDto.setNickname(authUser.getNickName());
            chatAdminDto.setLoginName(authUser.getLoginName());
            if(authUser.getImgPath()!=null&&!authUser.getImgPath().equals("")){
                chatAdminDto.setPhoto(ImagePropertiesConfig.AUTHUSER_IMAGE_SERVER_PATH + authUser.getImgPath());
            }else{
                chatAdminDto.setPhoto("");
            }
        }
        return chatAdminDto;
    }
    public ChatUserDto getChatUserDto(Long memberid){
        ChatUserDto chatUserDto = new ChatUserDto();
        Member member = memberService.findById(memberid);
        if(member!=null){
            chatUserDto.setMemberId(memberid);
            chatUserDto.setNickname(member.getNickName());
            if(member.getImgPath()!=null&&!member.getImgPath().equals("")){
                chatUserDto.setPhoto(ImagePropertiesConfig.MEMBER_IMAGE_SERVER_PATH + member.getImgPath());
            }else{
                chatUserDto.setPhoto("");
            }
            chatUserDto.setLoginName(member.getLoginName());
            if(member.getAdminRemark()!=null&&!member.getAdminRemark().equals("")){
                chatUserDto.setAdminRemark(member.getAdminRemark());
            }else{
                chatUserDto.setAdminRemark("");
            }

        }
        return chatUserDto;
    }


    /**
     * 管理员所有的客户列表
     * @param adminSid
     * @return
     */
    @RequestMapping(value = "/userInfoList", method = RequestMethod.GET)
    @ResponseBody
    public Object userInfoList(
            @RequestParam(name = "adminSid", required = true) String adminSid
    ) {
        if (StringUtils.isEmpty(adminSid)) {
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)) {
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        long adminId = user.getAdminId();
        List<Map<String,Object>> chatUserDtoList = new ArrayList<>();
        List<ChatSession> chatSessionList = chatSessionService.selectAllMemberByAdmin(adminId);
        for (ChatSession chatSession : chatSessionList) {
            Map<String,Object> datamap = new HashMap<>();
            ChatUserDto chatUserDto = this.getChatUserDto(chatSession.getMemberId());
            datamap.put("chatUserDto",chatUserDto);
            datamap.put("chatId",chatSession.getId());
            chatUserDtoList.add(datamap);
        }
        return Jsonp_data.success(chatUserDtoList);
    }
    /**
     * 搜索记录
     * @param adminSid
     * @param keyWord
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchMessage", method = RequestMethod.POST)
    public Object searchMessageAll(
            @RequestParam(name = "adminSid", required = true) String adminSid,
            @RequestParam(name = "chatId", required = true) long chatId,
            @RequestParam(name = "keyWord", required = true) String keyWord,
            @RequestParam(name = "pageIndex", required = true, defaultValue = "1") Integer pageIndex,
            //@RequestParam(name = "requestTimePoint", required = true, defaultValue = "n") String requestTimePoint,
            @RequestParam(name = "pageSize", required = false, defaultValue = PageConstant.APP_PAGE_SIZE + "") Integer pageSize
    ) {
        Map<String,Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(adminSid)){
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto adminDto = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, adminDto)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        long adminId = adminDto.getAdminId();

        ChatSession chatSession = chatSessionService.findById(chatId);
        if(chatSession!=null) {
            BasePagination<ChatRecord> page = new BasePagination<>();
            page.setLimit(pageSize);
            List<ChatRecordSearchDto> chatRecordSearchDtoList = ChatRecordSearchDto.transDtos(chatRecordService.searchByAdmin(chatId,keyWord,pageIndex,pageSize));


            resultMap.put("adminInfo",this.getChatAdminDto(chatSession.getAdminId()));
            resultMap.put("userInfo", this.getChatUserDto(chatSession.getMemberId()));
            Collections.reverse(chatRecordSearchDtoList);
            resultMap.put("msgList",chatRecordSearchDtoList);
            resultMap.put("chatId",chatId);
            return Jsonp_data.success(resultMap);
        }else{
            return Jsonp.error();
        }
    }



    /**
     * 删除Message
     * @param msgUniqueCodes
     * @param chatId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delMessage", method = RequestMethod.POST)
    public Object delMessage(
            @RequestParam(name = "adminSid", required = false) String adminSid,
            @RequestParam(name = "msgUniqueCodes", required = true) String msgUniqueCodes,
            @RequestParam(name = "chatId", required = true) long chatId
    ) {
        if (StringUtils.isEmpty(adminSid)){
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        //long adminId = user.getAdminId();
        int i = chatRecordService.delRecords(chatId,msgUniqueCodes);
        if(i>0){
            System.out.println("delMessage请求数据成功");
        }else{
            System.out.println("delMessage请求数据失败");
        }
        return Jsonp.success();
    }


    /**
     * 消息已读
     * @param adminSid
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/readMessage", method = RequestMethod.POST)
    public Object readMessage(
            @RequestParam(name = "adminSid", required = false) String adminSid,
            @RequestParam(name = "chatId", required = true) Long chatId
    ) {
        if (StringUtils.isEmpty(adminSid)){
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        long adminId = user.getAdminId();
        int i = chatRecordService.updateAdminUnReadRecord(chatId,adminId);
        if(i>0){
            System.out.println("readMessage请求数据成功");
        }else{
            System.out.println("readMessage请求数据失败");
        }
        return Jsonp.success();
    }

    /**
     * 会话转接
     * @param adminSid
     * @param chatId
     * @param newAdminId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changeAdminId", method = RequestMethod.POST)
    public Object updateSession(
            @RequestParam(name = "adminSid", required = true) String adminSid,
            @RequestParam(name = "chatId", required = true) long chatId,
            @RequestParam(name = "newAdminId", required = true) long newAdminId
    ) {
        if (StringUtils.isEmpty(adminSid)){
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }

        int i = chatSessionService.updateAdminSession(chatId, newAdminId);
        if(i>0){
            System.out.println("changeAdminId请求数据成功");
        }else{
            System.out.println("changeAdminId请求数据失败");
        }
        return Jsonp.success();
    }

    /**
     * 关闭会话
     * @param adminSid
     * @param chatId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/closeSession", method = RequestMethod.POST)
    public Object closeSession(
            @RequestParam(name = "adminSid", required = true) String adminSid,
            @RequestParam(name = "chatId", required = true) long chatId
    ) {
        if (StringUtils.isEmpty(adminSid)){
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        long adminId = user.getAdminId();
        int i = chatSessionService.adminCloseSession(chatId, adminId);
        if(i>0){
            System.out.println("closeSession请求数据成功");
        }else{
            System.out.println("closeSession请求数据失败");
        }
        return Jsonp.success();

    }
    /**
     * 拉黑会话
     * @param adminSid
     * @param chatId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/blackSession", method = RequestMethod.POST)
    public Object blackSession(
            @RequestParam(name = "adminSid", required = true) String adminSid,
            @RequestParam(name = "chatId", required = true) long chatId
    ) {
        if (StringUtils.isEmpty(adminSid)){
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }

        long adminId = user.getAdminId();
        int i = chatSessionService.blackSession(chatId, adminId);
        if(i>0){
            System.out.println("blackSession请求数据成功");
        }else{
            System.out.println("blackSession请求数据失败");
        }
        return Jsonp.success();
    }

    @ResponseBody
    @RequestMapping(value = "/topSession", method = RequestMethod.POST)
    public Object topSession(
            @RequestParam(name = "adminSid", required = true) String adminSid,
            @RequestParam(name = "chatId", required = true) long chatId

    ) {
        if (StringUtils.isEmpty(adminSid)){
            return Jsonp.paramError("adminSid不能为空!");
        }
        AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
        if (ObjectUtils.equals(null, user)){
            return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
        }
        long adminId = user.getAdminId();
        int i = chatSessionService.adminTopSession(chatId,adminId);
        if(i>0){
            System.out.println("topSession请求数据成功");
        }else{
            System.out.println("topSession请求数据失败");
        }
        return Jsonp.success();
    }


    /************************************resource************************************/
    /**
     *
     * @param adminSid
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    public Object fileUpload(
            @RequestParam(value="adminSid",required=true) String adminSid,
            //@RequestParam(value="widthToHeight",required=false) String widthToHeights,//以逗号分割，
            @RequestParam("file") MultipartFile[] file) {
        try {

            if (StringUtils.isEmpty(adminSid)){
                return Jsonp.paramError("adminSid不能为空!");
            }
            AdminDto user = (AdminDto) AdminRedisCache.getAdminDto(adminSid);
            if (ObjectUtils.equals(null, user)){
                return Jsonp.noLoginError(CommonConstant.CommonMessage.NO_LOGIN);
            }
            long adminId = user.getAdminId();


            ChatAdminDto chatAdminDto = new ChatAdminDto();
            chatAdminDto.setAdminId(adminId);

            //String widthToHeight [] = widthToHeights.split(",");
            List<String> widthToHeightList = new ArrayList<>();
            List<String> idList = new ArrayList<>();
            List<String> imgList = new ArrayList<>();
            for (int i = 0; i < file.length; i++) {
                boolean writeFileFromIS = false;
                MultipartFile multipartFile = file[i];
                InputStream inputStream = multipartFile.getInputStream();
                if (inputStream != null) {
                    Date now = new Date();
                    // 获取文件的名字
                    String filename = multipartFile.getOriginalFilename();
                    String suffix = filename.substring(filename.lastIndexOf(".") + 1);
                    long fileSize = multipartFile.getSize();
                    long timeMillis = System.currentTimeMillis();
                    String TIME_PATH = DateFormat.dateToYearMonth(now);
                    String articlePath = "chat";
                    // 文件类型目录+时间目录+时间戳名+文件后缀名
                    String FilePostfix = articlePath + "/" + TIME_PATH + "/" + timeMillis + "." + suffix;
                    // 首页功能管理目录文件路径（根目录+文件后缀）
                    String filePath = ImagePropertiesConfig.RESOURCE_PATH + FilePostfix;
                    writeFileFromIS = FileIOUtils.writeFileFromIS(filePath, inputStream);
                    if (writeFileFromIS) {
                        String imageUrl = ImagePropertiesConfig.RESOURCE_SERVER_PATH + FilePostfix;
                        Resource resource = new Resource();
                        resource.setArticleCode("AdminUpload");
                        resource.setArticleValue(chatAdminDto.getAdminId()+"");
                        resource.setFileFix(suffix);
                        resource.setFileMixName(timeMillis + "." + suffix);
                        resource.setFileName(filename);
                        resource.setFileSize(fileSize);
                        resource.setSource(3);
                        resource.setResCode(RandomNumUtil.getCharacterAndNumber(ChatConstant.RESOURCE_RESCODE_LEN));
                        resource.setTag("chat");
                        //存储相对路径
                        resource.setUrl(ImagePathUtil.getFileName(filePath));
                        resource.setCreateTime(now);
                        resource.setFileType(ResourceUtil.getFileTypeBySuffix(suffix));
                        resource.setIsDel(ChatConstant.IS_DEL_N);
                        //1上传  2下载
                        resource.setType(ChatConstant.RESOURCE_UPLOAD);
                       // resource.setWidthToHeight(widthToHeight[i]);
                        resourceService.add(resource);
                      //  widthToHeightList.add(widthToHeight[i]);

                        idList.add(resource.getId()+"");
                        imgList.add(imageUrl);
                    } else {
                        return Jsonp.error(multipartFile.getOriginalFilename() + "上传失败");
                    }
                }
            }

            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("idList", idList);
            resultMap.put("imgList", imgList);
            //resultMap.put("widthToHeightList", widthToHeightList);
            return Jsonp_data.success(resultMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Jsonp.error("文件上传异常,请稍后重试！");
    }


}
